/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.home.common;

import com.home.mapping.Attribute;
import com.home.mapping.Scheme;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



/**
 *
 * @author vi
 */
public class ApplicationCommon {

    public static Rectangle getRectangleForCenter(int mainW, int mainH, int dialogW, int dialogH) {
        return new Rectangle((mainW - dialogW) / 2, (mainH - dialogH) / 2, dialogW, dialogH);
    }

    public static double calculateResultOfAttribute(Attribute attr, Scheme scheme, long sumAttrNA, long groupdWeight) {
        Integer schemeValue = 0;
        DecimalFormat df = new DecimalFormat("##.#");
        if (scheme.getValue() != null) {
            schemeValue = scheme.getValue();
        }
        double preValue = ((double)attr.getAttributeWeight())/(groupdWeight - sumAttrNA);
        double newValue = attr.getAttributeWeight() + (preValue * sumAttrNA);
        return (Double.parseDouble(df.format(newValue * schemeValue / 100)));
    }
    
    public static double calculateResultOfAttributeWhenSelect(Attribute attr, Scheme scheme) {
        Integer schemeValue = 0;
        DecimalFormat df = new DecimalFormat("##.#");
        if (scheme.getValue() != null) {
            schemeValue = scheme.getValue();
        }
        return Double.parseDouble(df.format(((attr.getAttributeWeight() * schemeValue) / 100)));
    }

    public static SortedMap<String, ArrayList<Object>> collectionToHash(Collection list, String groupBy) {
        TreeMap<String, ArrayList<Object>> hash = new TreeMap<String, ArrayList<Object>>();

        for (Object obj : list) {
            Class<?> klass = obj.getClass();
            String groupByGetter = groupBy;

            try {
                // dynamic method invocation
                Method m = klass.getMethod(groupByGetter);
                Object result = m.invoke(obj);
                String resultAsKey = result.toString();

                ArrayList<Object> arrayList;
                if (hash.containsKey(resultAsKey)) {
                    arrayList = hash.get(resultAsKey);
                } else {
                    arrayList = new ArrayList<Object>();
                    hash.put(resultAsKey, arrayList);
                }
                arrayList.add(obj);

            } catch (Exception e) {
                
            }

            
        }
        return hash;
    }
    
    public static List<Integer> getSerialWeeks(int weekFrom, int weekTo) {
        List<Integer> weeks = new ArrayList<>();
        int range = weekTo - weekFrom + 1;
        for (int i = 0;i< range;i++) {
            weeks.add(weekFrom + i);
        }
        Collections.sort(weeks, new Comparator<Integer>() {
            @Override
            public int compare(Integer value1, Integer value2) {

                return value1.compareTo(value2);
            }
        });
        return weeks;
    }
    
    
    public void writeToExcell(JTable table, String path, String title, BufferedImage imgChart) {

        try {
            Workbook wb = new XSSFWorkbook(); //Excell workbook
            Sheet sheet = wb.createSheet(); //WorkSheet
            TableModel model = table.getModel(); //Table model
            int startTableRow = 4;
            if (imgChart != null) {
                startTableRow = 17;
                
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(imgChart, "png", os);
                InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
                //Get the contents of an InputStream as a byte[].
                byte[] bytes = IOUtils.toByteArray(inputStream);

                //Adds a picture to the workbook
                int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
                //close the input stream
                inputStream.close();

                //Returns an object that handles instantiating concrete classes
                CreationHelper helper = wb.getCreationHelper();

                //Creates the top-level drawing patriarch.
                Drawing drawing = sheet.createDrawingPatriarch();

                //Create an anchor that is attached to the worksheet
                ClientAnchor anchor = helper.createClientAnchor();
                //set top-left corner for the image
                anchor.setCol1(1);
                anchor.setRow1(2);

                //Creates a picture
                Picture pict = drawing.createPicture(anchor, pictureIdx);
                //Reset the image to the original size
                pict.resize();

            }
            
            // title
            Row rowTitle = sheet.createRow(0);
            CellStyle titleStyle = wb.createCellStyle();
            Font font = wb.createFont();
            font.setColor(HSSFColor.BLACK.index);
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            titleStyle.setFont(font);
            Cell cellTitle = rowTitle.createCell(7);
            cellTitle.setCellStyle(titleStyle);
            cellTitle.setCellValue(title);
            
            
            
            //header
            Row headerRow = sheet.createRow(startTableRow); //Create row at line 0
            CellStyle headerStyle = wb.createCellStyle();
            Font fontHeader = wb.createFont();
            font.setColor(HSSFColor.BLACK.index);
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            headerStyle.setFont(fontHeader);
            for (int headings = 0; headings < model.getColumnCount(); headings++) { //For each column
                Cell cellHeader = headerRow.createCell(headings);
                cellHeader.setCellStyle(headerStyle);
                cellHeader.setCellValue(model.getColumnName(headings));//Write column name
            }

            // data
            Row dataRow = sheet.createRow(startTableRow + 1);
            CellStyle dataStyle = wb.createCellStyle();
            dataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            dataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            dataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            dataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            for (int rows = 0; rows < model.getRowCount(); rows++) { //For each table row
                for (int cols = 0; cols < table.getColumnCount(); cols++) { //For each table column
                    Cell cellData = dataRow.createCell(cols);
                    
                    cellData.setCellStyle(dataStyle);
                    cellData.setCellValue(model.getValueAt(rows, cols).toString()); //Write value
                }

                //Set the row to the next one in the sequence 
                dataRow = sheet.createRow((rows + startTableRow + 2));
                
            }
            wb.write(new FileOutputStream(path.toString()));//Save the file  
        } catch (Exception e) {
        }

    }
}
